#ifndef __IOTHREADPOLL_H__
#define __IOTHREADPOLL_H__

#include <pthread.h>
#include <atomic>
#include <unistd.h>
#include "qSingleton.h"
#include "connection.h"

#define IO_THREADS_MAX_NUM 128
#define IO_THREADS_OP_READ 1
#define IO_THREADS_OP_WRITE 2

class IOThreadPool : public qSingleton<IOThreadPool>
{
    friend qSingleton<IOThreadPool>;
protected:
    IOThreadPool();
    ~IOThreadPool();

public:
    IOThreadPool(const IOThreadPool&) = delete;
    IOThreadPool& operator=(const IOThreadPool&) = delete;

    int getIOPendingCount(int i);
    void setIOPendingCount(int i, int count);
    bool postponeClientRead(connection* conn);
    static int readQueryFromClient(connection* conn);
    static int writeToClient(connection* conn, int handle_install = 0);
    static int sendReplyToClient(connection* conn);

    static void* IOThreadMain(void* arg);
    void InitThreadIO();

    void startThreadIO();
    void stopThreadIO();

    void pushThreadList(int i, connection* conn);
    int getThreadListSize(int i);
    void setThreadOperation(int op);
    void handleReadTask(int i);
    void handleWriteTask(int i);
    void handleTask(int i);

    void waitIOThread(int i);
public:
    //每个io线程的任务队列
    std::list<connection*> io_thread_list_[IO_THREADS_MAX_NUM];
    //io线程的锁，这个锁主要是用来主线程控制是否需要使用io线程的
    //当任务量少不适用io线程池，主线程拥有锁，让io线程等待
    pthread_mutex_t io_thread_mutex_[IO_THREADS_MAX_NUM];
    //线程任务数，即队列长度
    std::atomic_int io_threads_pending[IO_THREADS_MAX_NUM];
    //保存io线程的tid
    pthread_t io_threads[IO_THREADS_MAX_NUM];
    //执行什么任务，读或者写
    int io_thread_op_;
};

#endif
